package zh.dummy.netty.server.handler;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import zh.dummy.netty.core.protocol.MessageType;
import zh.dummy.netty.core.protocol.NettyMessage;
import zh.dummy.netty.server.context.listener.WorkflowListener;
import zh.dummy.netty.server.util.NettyUtil;

public class WorkflowHandler extends ChannelHandlerAdapter{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private Set<WorkflowListener> listeners = new CopyOnWriteArraySet<WorkflowListener>();
	
	public WorkflowHandler(){
		this.listeners.addAll(NettyUtil.getListeners());
	}

	public void channelRead(ChannelHandlerContext ctx,Object msg){
		NettyMessage message = (NettyMessage)msg;
		if(message.getHeader() != null
				&& message.getHeader().getType() == MessageType.WORK_FLOW.getValue()){
			if(logger.isDebugEnabled()){
				logger.debug("reveived work_flow message : {}",new Object[]{message.toString()});
			}
			onListeners(message);
		}else{
			ctx.fireChannelRead(msg);
		}
	}

	private void onListeners(NettyMessage message) {
		if(message.getBody() == null
				|| message.getBody().size() == 0){
			if(logger.isDebugEnabled()){
				logger.debug("reveived message body is empty");
			}
			return;
		}
		
		for(WorkflowListener listener : listeners){
			listener.onMessage(message.getBody());
		}
	}


	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
		ctx.close();
		ctx.fireExceptionCaught(cause);
	}
	
}
